import re
from rest_framework import serializers
from user.models import Address, User
from areas.models import Area


class AreasSerializer(serializers.ModelSerializer):

    class Meta:
        model = Area
        fields = ('id', 'name')


class AddressSerializer(serializers.ModelSerializer):
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def validate(self, attrs):
        if not re.match(r'^1[3-9]\d{9}$', attrs['mobile']):
            raise serializers.ValidationError('手机格式错误')

        return attrs

    def create(self, validated_data):

        user = self.context['request'].user

        validated_data['user'] = user

        address = super().create(validated_data)

        return address














